package com.cx.mall.seckill.service.impl;

import com.cx.mall.api.AlipayFeign;
import com.cx.mall.api.order.OrderDetailFeign;
import com.cx.mall.api.order.OrderInfoFeign;
import com.cx.mall.common.model.order.OrderInfo;
import com.cx.mall.common.utils.ResponseEnum;
import com.cx.mall.common.utils.ResponseVO;
import com.cx.mall.seckill.service.IBuyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BuyServiceImpl implements IBuyService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private OrderInfoFeign orderInfoFeign;
    @Autowired
    private OrderDetailFeign orderDetailFeign;
    @Autowired
    private AlipayFeign paymentFeign;
    @Autowired
    private AlipayFeign alipayFeign;

    @Override
    @Transactional
    public void dcount(int activityId, String skuId) throws Exception {
        // 提取商品ID
        String key = "seckill-" + activityId + "-" + skuId;
        // 提取商品库存
        int count = Integer.parseInt(redisTemplate.opsForValue().get(key));
        // 如果库存大于0，则减1
        if(count > 0){
            redisTemplate.opsForValue().decrement(key);
            //远程调用订单服务（新增订单记录）
            // 2. 创建订单
            OrderInfo orderInfo = new OrderInfo();
            ResponseVO<Long> orderSaveResult = orderInfoFeign.save(orderInfo);
            if (orderSaveResult.getCode() != ResponseEnum.SUCCESS.getCode()) {
                // 订单创建失败，回补库存
                redisTemplate.opsForValue().increment(key);
                throw new RuntimeException("订单创建失败：" + orderSaveResult.getMessage());
            }
            String orderId = String.valueOf(orderSaveResult.getData()); // 获取订单ID
            //远程调用订单服务（新增订单详情记录）
            ResponseVO<Boolean> detailSaveResult = orderDetailFeign.save(orderId, skuId);
            if (detailSaveResult.getCode() != ResponseEnum.SUCCESS.getCode()) {
                // 详情创建失败，回滚订单和库存
                orderInfoFeign.deleteById(orderId); // 假设存在删除订单接口
                redisTemplate.opsForValue().increment(key);
                throw new RuntimeException("订单详情创建失败：" + detailSaveResult.getMessage());
            }

            //发起支付
            ResponseVO<String> payResult = alipayFeign.query(orderId);
            if (payResult.getCode() != ResponseEnum.SUCCESS.getCode()) {
                // 支付发起失败，回滚订单、详情和库存
                orderInfoFeign.deleteById(orderId);
                redisTemplate.opsForValue().increment(key);
                throw new RuntimeException("支付发起失败：" + payResult.getMessage());
            }
            String payUrl = payResult.getData(); // 支付链接（前端需引导用户跳转）
            System.out.println("支付链接：" + payUrl); // 实际应返回给前端
            //发起支付回查
        }else {
            throw new RuntimeException(ResponseEnum.STOCK_NOT_ENOUGH.getMessage());
        }
    }
}
